import json
from django.db.models import Q
from django.http import HttpResponse
from rest_framework import status,mixins
from rest_framework.filters import SearchFilter
from rest_framework.generics import GenericAPIView
from rest_framework.response import Response
from rest_framework_simplejwt.exceptions import TokenError, InvalidToken
from rest_framework_simplejwt.views import TokenObtainPairView
from rest_framework.views import APIView
from rest_framework.viewsets import GenericViewSet

from .pagination import ResultsSetPagination
from .permissions import IsOwnerOrReadOnly
from .serializers import UserSerializer, DisordersTypeSerializer, UserDataSerializer, QuestionnaireSerializer, \
    QuestionItemSerializer, EmgDataSerializer, LiteratureKnowledgeSerializer, MagneticStimulusPrescriptionsSerializer, \
    ElectricalStimulusPrescriptionsSerializer, PatientCaseSerializer
from rest_framework.permissions import IsAuthenticated

from app.models import User, DisordersType, UserData, Questionnaire, QuestionItem, ScoreResult, LiteratureKnowledge, \
    MagneticStimulusPrescriptions, ElectricalStimulusPrescriptions, PatientCase

from common.scoreresult import score_result_all
class RegisterView(APIView):
    # 注册
    def post(self, request):
        # 接收用户参数
        username = request.data.get('username')
        password = request.data.get('password')
        password_confirmation = request.data.get('password_confirmation')
        if not all([username,password,password_confirmation]):
            return Response({'code':500,'msg':"参数为空"}, status=status.HTTP_200_OK)
        if User.objects.filter(username = username).exists():
            return Response({'code':500,'msg': "用户名已存在"}, status=status.HTTP_200_OK)
        if password != password_confirmation:
            return Response({'code':500,'msg': "两次密码不一致"}, status=status.HTTP_200_OK)
        if not 6<=len(password)<=18:
            return Response({'code':500,'msg': "密码长度需要再6到18位之间"}, status=status.HTTP_200_OK)
        obj = User.objects.create_user(username=username,password=password,email="")
        res = {
            "username": username,
            'id': obj.id,
        }
        return Response(res, status=status.HTTP_200_OK)

class LoginView(TokenObtainPairView):
    # 登录
    def post(self, request, *args, **kwargs):
        serializer = self.get_serializer(data=request.data)
        try:
            serializer.is_valid(raise_exception=True)
        except TokenError as e:
            raise InvalidToken(e.args[0])
        #自定义登录成功返回
        result = serializer.validated_data
        result['email'] = serializer.user.email
        result['token'] = result.pop('access')
        return Response(result, status=status.HTTP_200_OK)


class UserView(GenericViewSet,mixins.RetrieveModelMixin):
    """用户相关操作"""
    queryset = User.objects.all()
    serializer_class = UserSerializer
    # 设置认证用户才能访问
    permission_classes = [IsAuthenticated,IsOwnerOrReadOnly]

    def upload_file(self,requst,*args,**kwargs):
        # 获取全部参数 request.data
        # 获取当前用户 request.user
        pass


class DisordersTypeView(APIView):
    permission_classes = [IsAuthenticated]
    def post(self, request):
        ser = DisordersTypeSerializer(data=request.data)
        if ser.is_valid():
            ser.save()
            return Response(ser.data, status=status.HTTP_200_OK)
        return Response(data=ser.errors, status=400)

    def get(self,request):
        obj = DisordersType.objects.all()
        ser = DisordersTypeSerializer(instance=obj, many=True)
        return Response(ser.data, status=status.HTTP_200_OK)

class UserDataInfoView(APIView):
    permission_classes = [IsAuthenticated]
    def get(self, request, pk, format=None):
        obj = UserData.get(id=pk)
        ser = UserDataSerializer(instance=obj)
        return Response(ser.data, status=status.HTTP_200_OK)

class UserDataList(APIView):

    def get(self,request):
        seach = request.query_params.get('search')
        if(seach):
            userdata = UserData.objects.all().filter(
                Q(user_name__icontains = seach) | Q(medical_record_num__icontains = seach)
            ).order_by('id')
        else:
            userdata = UserData.objects.all().order_by('id')

        page = ResultsSetPagination()
        # 在数据库中获取分页的数据
        page_list = page.paginate_queryset(userdata, request, view=self)
        # 获取所有的类型
        DisordersTypes = DisordersType.objects.all()
        DisordersTypeMap = {}
        for Disorders in DisordersTypes:
            DisordersTypeMap[str(Disorders.id)] =  Disorders

        #问卷调查所有问题
        Questionnaires = Questionnaire.objects.all()
        QuestionnaireMap = {}
        for questionnaire in Questionnaires:
            QuestionnaireMap[str(questionnaire.id)] = questionnaire

        QuestionItems = QuestionItem.objects.all()
        QuestionItemMap = {}
        for item in QuestionItems:
            QuestionItemMap[str(item.id)] = item
        resultMap = {}
        resultMap["count"] = userdata.count()
        rest = []
        for userData in page_list:
            restMap = {}
            restMap['id'] = userData.id
            restMap['user_name'] = userData.user_name
            restMap['medical_record_num'] = userData.medical_record_num
            scoreResults = ScoreResult.objects.filter(user_data_id = userData.id)
            for scoreResult in scoreResults:
                scoreResultMap = {}
                question_result = scoreResult.question_result.split(',')
                scoreResultMap['total_score_result'] = scoreResult.total_score_result
                scoreResultMap['total_score'] = scoreResult.total_score
                for questionId in question_result:
                    item = {}
                    item['id'] = QuestionItemMap[str(questionId)].id
                    item['score'] = QuestionItemMap[str(questionId)].score
                    item['question_id'] = QuestionItemMap[str(questionId)].question_id
                    item['issue_select'] = QuestionItemMap[str(questionId)].issue_select
                    item['question'] = QuestionnaireMap[QuestionItemMap[str(questionId)].question_id].question
                    scoreResultMap[str(QuestionItemMap[str(questionId)].question_id)]=item
                restMap[scoreResult.disorders_type] = scoreResultMap
            rest.append(restMap)
            resultMap["results"] = rest
        return Response(data=resultMap, status=status.HTTP_200_OK)

class UserDataView(APIView):
    permission_classes = [IsAuthenticated]
    def post(self, request):
        request.data['user_id'] = request.user.id
        ser = UserDataSerializer(data= request.data)
        if ser.is_valid():
            ser.save()
            return Response(ser.data, status=status.HTTP_200_OK)
        return Response(data=ser.errors, status=400)

    def put(self, request):
        data = request.data
        UserData.objects.filter(id=data["id"]).update(**data)
        return Response(request.data, status=status.HTTP_200_OK)

    def get(self, request):
        obj = UserData.objects.filter(user_id=request.user.id).order_by("-create_time")
        ser = UserDataSerializer(instance=obj, many=True)
        return Response(ser.data, status=status.HTTP_200_OK)

class QuestionnaireInfoView(APIView):
    def get(self, request, pk, format=None):
        obj = Questionnaire.objects.filter(disorders_type = pk)
        result = []
        for o in obj:
            questionItems = QuestionItem.objects.filter(question_id = o.id)
            questionItemArray = []
            for questionItem in questionItems:
                questionItemArray.append({
                    "issue_select": questionItem.issue_select,
                    "score": questionItem.score,
                    "id": questionItem.id
                })
            result.append({
                "id": o.id,
                "disorders_type": o.disorders_type,
                "question": o.question,
                "questionItems": questionItemArray
            })
        return Response(result, status=status.HTTP_200_OK)

class QuestionnaireView(APIView):
    def post(self, request):
        ser = QuestionnaireSerializer(data=request.data)
        if ser.is_valid():
            ser.save()
            return Response(ser.data, status=status.HTTP_200_OK)
        return Response(data=ser.errors, status=400)
    def get(self, request):
        obj = Questionnaire.objects.all()
        ser = QuestionnaireSerializer(instance=obj, many=True)
        return Response(ser.data, status=status.HTTP_200_OK)

class QuestionItemView(APIView):
    def post(self, request):
        ser = QuestionItemSerializer(data=request.data)
        if ser.is_valid():
            ser.save()
            return Response(ser.data, status=status.HTTP_200_OK)
        return Response(data=ser.errors, status=400)
    def get(self, request):
        obj = QuestionItem.objects.all()
        ser = QuestionItemSerializer(instance=obj, many=True)
        return Response(ser.data, status=status.HTTP_200_OK)

class EmgDataView(APIView):
    def post(self, request):
        ser = EmgDataSerializer(data=request.data)
        if ser.is_valid():
            ser.save()
            return Response(ser.data, status=status.HTTP_200_OK)
        return Response(data=ser.errors, status=400)

class Prescription(APIView):
    def post(self,request):
        # 获取分数
        score = request.data.get('score')
        # kegel强度
        kegelqd = {1:10,2:12,3:13,4:14,5:15,6:16,7:17,8:18,9:19,10:21,11:22,12:24,13:25,14:26,15:27,16:29,17:31,18:33,19:35,20:37,21:40}
        # kegel治疗时间
        kegelzlsj = { 1:1,2:1,3:2,4:2,5:3,6:3,7:4,8:5,9:6,10:7,11:8,12:9,13:9,14:10,15:11,16:11,17:12,18:13,19:14,20:15,21:15}
        # kegel收缩时间
        kegelsssj = {1:1,2:1,3:2,4:2,5:3,6:3,7:3,8:4,9:4,10:5,11:5,12:6,13:6,14:17,15:7,16:8,17:8,18:9,19:9,20:10,21:10}
        # 电刺激 电流强度
        dcjqd = {1:1,2:4,3:6,4:9,5:11,6:14,7:16,8:18,9:21,10:24,11:27,12:30,13:32,14:34,15:36,16:39,17:41,18:44,19:46,20:48,21:50}
        # 电刺激 治疗时间
        dcjzlsj = {1:1,2:1,3:2,4:3,5:3,6:4,7:4,8:5,9:5,10:6,11:7,12:8,13:9,14:10,15:11,16:11,17:12,18:13,19:13,20:14,21: 15}
        # 电刺激 频率
        dcjpl = {1: 15, 2: 18, 3: 23, 4: 26, 5: 28, 6: 32, 7: 35, 8: 38, 9: 41, 10: 44, 11: 47, 12: 51, 13: 54, 14: 57,
                 15: 61, 16: 64, 17: 66, 18: 69, 19: 73, 20: 76, 21: 79}
        return Response({
                    "kegelqd": kegelqd[score],
                    "kegelzlsj": kegelzlsj[score],
                    "kegelsssj": kegelsssj[score],
                    "dcjqd": dcjqd[score],
                    "dcjzlsj": dcjzlsj[score],
                    "dcjpl": dcjpl[score]
                }, status=status.HTTP_200_OK)

class ScoreResultView(APIView):
    def post(self, request):
        user_data_id = request.data.get('user_data_id')
        question_result = request.data.get('question_result')
        disorders_type = request.data.get('disorders_type')
        if not all([user_data_id,question_result,disorders_type]):
            return Response({'error':"参数为空"}, status=status.HTTP_400_BAD_REQUEST)
        objs = QuestionItem.objects.filter(id__in=list(question_result.split(',')))
        total_score = 0
        total_score_result = None
        if len(objs) > 0:
            if (disorders_type != '7'):
                for o in objs:
                    total_score += int(o.score)
                # print(str(total_score))
                score_result_dic = score_result_all.get(disorders_type)
                for key in score_result_dic.keys():
                    key_array = key.split("-")
                    if int(key_array[0]) <= total_score <= int(key_array[1]):
                        # 评分判断结果
                        total_score_result = score_result_dic.get(key)
                        break

            else:
                objs = list(filter(lambda x: x.score != '0', objs))
                # 评分判断结果
                total_score_result = objs[0].score
            ScoreResult.objects.create(user_data_id = user_data_id,
                                       question_result=question_result,
                                       total_score=total_score,
                                       total_score_result=total_score_result,
                                       disorders_type= disorders_type)
        else:
            return Response({'error': "问卷结果不存在"}, status=status.HTTP_400_BAD_REQUEST)

        return Response({
            "total_score": total_score,
            "total_score_result": total_score_result,
            "disorders_type": disorders_type
        }, status=status.HTTP_200_OK)


class LiteratureKnowledgeView(GenericViewSet,mixins.ListModelMixin,mixins.CreateModelMixin):
    queryset = LiteratureKnowledge.objects.all()
    pagination_class = ResultsSetPagination
    serializer_class = LiteratureKnowledgeSerializer

    filter_backends = [SearchFilter]
    search_fields = ['details','contraindications','two_type']
    # def get(self,request):
    #     obj = self.get_queryset()
    #     # Serializer = self.get_serializer_class()
    #     # ser = Serializer(instance=obj, many=True)
    #     ser = self.get_serializer(obj, many=True)
    #     return Response(ser.data, status=status.HTTP_200_OK)

class LiteratureKnowledgeInfo(GenericViewSet,mixins.RetrieveModelMixin,mixins.UpdateModelMixin,mixins.DestroyModelMixin):
    queryset = LiteratureKnowledge.objects.all()
    serializer_class = LiteratureKnowledgeSerializer


class MagneticStimulusPrescriptionsView(GenericViewSet,mixins.ListModelMixin,mixins.CreateModelMixin):
    queryset = MagneticStimulusPrescriptions.objects.all()
    pagination_class = ResultsSetPagination
    serializer_class = MagneticStimulusPrescriptionsSerializer
    filter_backends = [SearchFilter]
    search_fields = ['indication', 'protocol_name', 'stimulation_site']


class MagneticStimulusPrescriptionsInfo(GenericViewSet,mixins.RetrieveModelMixin,mixins.UpdateModelMixin,mixins.DestroyModelMixin):
    queryset = MagneticStimulusPrescriptions.objects.all()
    serializer_class = MagneticStimulusPrescriptionsSerializer


class ElectricalStimulusPrescriptionsView(GenericViewSet,mixins.ListModelMixin,mixins.CreateModelMixin):
    queryset = ElectricalStimulusPrescriptions.objects.all()
    pagination_class = ResultsSetPagination
    serializer_class = ElectricalStimulusPrescriptionsSerializer
    filter_backends = [SearchFilter]
    search_fields = ['category', 'name']


class ElectricalStimulusPrescriptionsInfo(GenericViewSet,mixins.RetrieveModelMixin,mixins.UpdateModelMixin,mixins.DestroyModelMixin):
    queryset = ElectricalStimulusPrescriptions.objects.all()
    serializer_class = ElectricalStimulusPrescriptionsSerializer


def testview(request):

    # 从数据库读取数据
    # rs = PatientCase.objects.filter(patient_id=2).first()
    # print(rs.patient_id,rs.score1)

    if request.method == 'POST':
        # 通过 request.body 获取原始数据
        
        # data = json.loads(request.body)  # 解析 JSON 数据
        # name = data.get('name')
        # score1 = data.get('score1')
        data = json.loads(request.body)
        print(data)

        serializer = PatientCaseSerializer(data=data)

        if serializer.is_valid():
            # 保存数据到数据库
            serializer.save()
            print('save success')
            
        else:
            1/0
            print(serializer.errors)
        
        # 处理数据
        # print(name,score1)
            
    return HttpResponse("success")  






